﻿using System.Collections.ObjectModel;
using System.Net.Sockets;

namespace TouchFish.Media.Net;

public class Tcp
{
    // Timeout Constants
    public const int ReceiveTimeout = 15000;
    public const int SendTimeout = 15000;

    private TcpClient? _tcp;
    private NetworkStream? _stream;
    private BinaryWriter? _writer;

    public bool Connected => _tcp != null && _tcp.Connected;

    public void Connect(string host, int port)
    {
        if (host == null) throw new ArgumentNullException(nameof(host));

        _tcp = new TcpClient { NoDelay = true };
        _tcp.ReceiveTimeout = ReceiveTimeout;
        _tcp.SendTimeout = SendTimeout;
        _tcp.Connect(host, port);
        _stream = _tcp.GetStream();
        _stream.ReadTimeout = ReceiveTimeout;
        _stream.WriteTimeout = SendTimeout;

        _writer = new BinaryWriter(_stream);
    }


    /// <summary>
    /// Closes the connection to the remote host.
    /// </summary>
    public void Close()
    {
        try
        {
            _writer?.Close();
            _stream?.Close();
            _tcp?.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }


    public void WriteData(byte[] response)
    {
        if (_writer == null)
            return;
        _writer.Write(response, 0, response.Length);
        _writer.Flush();
    }
}